package session;

import entity.IndicativeProductPrice;
import entity.PurchaseOrder;
import entity.PurchaseOrderItem;
import entity.Quotation;
import entity.QuotationItem;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import javax.ejb.LocalBean;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author K_M
 */
@Stateful
@LocalBean
public class PurchaseOrderManager {

    @PersistenceContext
    private EntityManager em;
    private PurchaseOrder purchaseOrder;
    private PurchaseOrderItem purchaseOrderItem;
    private Collection<PurchaseOrderItem> purchaseOrderItemList=new ArrayList<PurchaseOrderItem>();
    private Collection<PurchaseOrder> purchaseOrderList = new ArrayList<PurchaseOrder>();
    private Collection<QuotationItem> quotationItemList=new ArrayList<QuotationItem>();
    private Collection<IndicativeProductPrice> productList;
    private boolean matches = false; //if quotation matches with purchase order, then true

    public void createPurchaseOrder(Long quotationId) //NOT FULL CREATION; USE OF DUMMY DATA
    {
        purchaseOrder = new PurchaseOrder();
        purchaseOrder.setQuotationId(quotationId);
        purchaseOrder.setSubmittedBy("User"); //should be extracted from user session
        Date today = new java.util.Date();
        Timestamp dateOrdered = new Timestamp(today.getTime());
        purchaseOrder.setDateSubmitted(dateOrdered);
    }

    public void addPurchaseOrderItem(Collection<PurchaseOrderItem> purchaseOrderItems) {
        purchaseOrderItemList = new ArrayList<PurchaseOrderItem>();
        for (Object o : purchaseOrderItems) {
            PurchaseOrderItem temp = (PurchaseOrderItem) o;
            purchaseOrderItemList.add(temp);
        }
        purchaseOrder.setPurchaseOrderItems(purchaseOrderItemList);
    }

    public Collection<IndicativeProductPrice> getProductList() {
        productList = new ArrayList<IndicativeProductPrice>();
        Query q = em.createQuery("Select i From Product i");
        for (Object o : q.getResultList()) {
            IndicativeProductPrice temp = (IndicativeProductPrice) o;
            productList.add(temp);
        }
        return productList;
    }

    public Collection<PurchaseOrderItem> getPurchaseOrderItemList(Long purchaseOrderId) { //returns a list of purchase order items
        PurchaseOrder p=em.find(PurchaseOrder.class, purchaseOrderId) ;
        return p.getPurchaseOrderItems();

        /* OLD VERSION
                purchaseOrderItemList = new ArrayList<PurchaseOrderItem>();
        Query q = em.createQuery("Select i From PurchaseOrderItem i where");
        for (Object o : q.getResultList()) {
            PurchaseOrderItem temp = (PurchaseOrderItem) o;
            purchaseOrderItemList.add(temp);
        }
        return purchaseOrderItemList; */
    }

    public boolean matchQuotationPurchaseOrder(PurchaseOrder p, Quotation q,
            Collection<PurchaseOrderItem> pItemList, Collection<QuotationItem> qItemList) {
        System.out.println("Product id: "+p.getId()+"\tQuotation id: "+q.getId());
        
        //Check if expired (Timestamp dateTime, Integer daysValid); To spilt into another method
                Long dateQuoted = q.getDateTime().getTime(); //convert Timestamp to Long
        
        //convert DaysValid to milliseconds and get the expiry date
        Long dateExpired =dateQuoted+(24 * 60 * 60 * 1000 * q.getDaysValid().longValue());
        Date today = new Date();
        if ((today.getTime() > dateExpired)) { //today's date(in Long)>expiryDate(in Long)
            return false;
        } else {
            //check for each of their respective Items if they match
            //IMPT ASSUMPTION: Items must be added in the same order!
            for (QuotationItem qu : qItemList) {
                for (PurchaseOrderItem o : pItemList) {
                    if (o.getProductName().equals(qu.getProductName())) {
                        if (o.getProductPrice().equals(qu.getProductPrice())) {
                            //if (o.getNumOfProduct().equals(qu.getNumOfProduct())) {
                                matches = true;
                            //}
                        }
                    }
                    if (matches == true) {
                        break; //check next item
                    }
                }
                if (matches == false) {
                    break; //does not match, exit loop
                }
            }
            return matches;

            /* OLD VERSION
            for (QuotationItem qu : qItemList) {
                for (PurchaseOrderItem o : pItemList) {
                    if (!o.getProductName().equals(qu.getProductName())) { //does not match product name
                        System.out.println("Purchase: "+o.getProductName()+"\tQuotation: "+qu.getProductName()); //TEST
                        matches = false;
                        System.out.println("Product Name not match"); //TEST
                        break;
                    }
                    if (!o.getNumOfProduct().equals(qu.getNumOfProduct())) { //does not match num of product
                        matches = false;
                        System.out.println("Product Num not match"); //TEST
                        break;
                    }
                    if (!o.getProductPrice().equals(qu.getProductPrice())) { //does not match product price
                        matches = false;
                        System.out.println("Product Price not match"); //TEST
                        break;
                    }
                }
                if (matches == false) {
                    break;
                }
            }
            return matches; */
        }
    }

        public Double calculateTotalPrice() {

        Double tempTotal = 0.0;
        for (Object o : purchaseOrder.getPurchaseOrderItems()) {
            PurchaseOrderItem temp = (PurchaseOrderItem) o;
            tempTotal += temp.getProductPrice() * temp.getNumOfProduct();
        }
        return (Math.round(tempTotal * 100)) / 100.0;
    }

    public void persist() {
        Double temp = calculateTotalPrice();
        temp = (Math.round(temp * 100)) / 100.0;
        purchaseOrder.setTotalPrice(temp);
        em.persist(purchaseOrder);
        em.flush();
    }

    public PurchaseOrder getPurchaseOrder() {
        return purchaseOrder;
    }

    public PurchaseOrder getPurchaseOrder(Long id) {
        PurchaseOrder s;
        s = em.find(PurchaseOrder.class, id);
        return s;
    }

    public Collection<PurchaseOrderItem> getPurchaseOrderItem() {
        return purchaseOrder.getPurchaseOrderItems();
    }

    public Collection<PurchaseOrderItem> getPurchaseOrderItem(Long id) {
        PurchaseOrder s;
        s = em.find(PurchaseOrder.class, id);
        return s.getPurchaseOrderItems();
    }

    public void updatePurchaseOrderSubmittedBy(Long id, String usr) {
        PurchaseOrder o = em.find(PurchaseOrder.class, id);
        o.setSubmittedBy(usr);
        em.flush();
    }

    public void deletePurchaseOrder(Long id) {
        PurchaseOrder o = em.find(PurchaseOrder.class, id);
        em.remove(o);
        em.flush();
    }

    public void merge(PurchaseOrder s) {
        em.merge(s);
        em.flush();
    }

    public void setPurchaseOrderList(Collection<PurchaseOrder> purchaseOrderList) {
        this.purchaseOrderList = purchaseOrderList;
    }

    public Collection<PurchaseOrder> getPurchaseOrderList() {
        purchaseOrderList = new ArrayList<PurchaseOrder>();
        Query q = em.createQuery("Select i From PurchaseOrder i");
        for (Object o : q.getResultList()) {
            PurchaseOrder temp = (PurchaseOrder) o;
            purchaseOrderList.add(temp);
        }
        return purchaseOrderList;
    }

    public Collection<PurchaseOrder> getPurchaseOrderList(String clientUsername) {
        Query q = em.createQuery("Select i From PurchaseOrder i where i.submittedBy=:clientUsername");
        q.setParameter("clientUsername", clientUsername);
        for (Object o : q.getResultList()) {
            PurchaseOrder temp = (PurchaseOrder) o;
            purchaseOrderList.add(temp);
        }
        return purchaseOrderList;
    }
}
